var express = require('express');
var router = express.Router();
var FormData = require('form-data');
const crypto = require('crypto');
var config = require("../config");

router.use(function (req, res, next) {
  if (req.session.username) {
    next();
  } else {
    res.render('login');
  }
});

router.get('/', function (req, res, next) {
  res.render('index');
});
router.post('/', function (req, res, next) {
  var desJS = require('../gm/describe');
  res.send(desJS);
});
router.post('/gm', function (req, res, next) {
  let fileName = "../gm/" + req.body.id;
  let gmJS = require(fileName);
  if (!gmJS) res.status(404).send("ERROR");
  res.send(gmJS);
});
router.post('/commit', function (req, res, next) {
  console.log(req.ip);
  console.log(req.body);
  send2Idip(req.body);
  res.send("success");
});

var send2Idip = function (obj) {
  var serv = 'serv' + obj.server;
  var cfg = config[serv];
  if (!cfg) return;
  var request_url = 'http://' + cfg.ip + ':' + cfg.port;
  let form = new FormData();
  delete obj.server;
  form.append("auth", aesEncrypt());
  form.append("content", JSON.stringify(obj));
  form.submit(request_url, function (err, res) {
    if (err) console.log(err);
  });
}

function aesEncrypt() {
  let secret = config.secret;
  let data = Date.now().toString();
  const cipher = crypto.createCipher('aes256', secret);
  var crypted = cipher.update(data, 'utf8', 'hex');
  crypted += cipher.final('hex');
  return crypted;
}

module.exports = router;
